package com.sunxd.zstudy.designPattern.support.proxy.cglib;

import org.springframework.cglib.core.DebuggingClassWriter;
import org.springframework.cglib.proxy.Enhancer;
import org.springframework.cglib.proxy.MethodInterceptor;
import org.springframework.cglib.proxy.MethodProxy;

import java.lang.reflect.Method;

/**
 * @author: sun.xd
 * @date: 2021-10-19 15:26
 **/
public class CglibProxy {

    public static void main(String[] args) {

        System.setProperty(DebuggingClassWriter.DEBUG_LOCATION_PROPERTY,"/Users/duandian/IdeaProjects/sxd-project");
        Enhancer enhancer = new Enhancer();
        enhancer.setSuperclass(CglibProxy.class);
        enhancer.setCallback(new MyMethodInterceptor());
        CglibProxy dog = (CglibProxy) enhancer.create();
        dog.eat();
    }

    public String eat(){
        System.out.println("eat food");
        return "dog eat";
    }

    static class MyMethodInterceptor implements MethodInterceptor{

        @Override
        public Object intercept(Object o, Method method, Object[] objects, MethodProxy methodProxy) throws Throwable {
            System.out.println(o.getClass().getName());
            System.out.println(o.getClass().getSuperclass().getName());
            System.out.println(method.getName());
            System.out.println("before");
            Object o1 = methodProxy.invokeSuper(o, objects);
            System.out.println("end");
            return o1;
        }
    }

}
